﻿@inject IBlogService Service
@inject IMarkdownRenderService MarkdownService
@inject MessageService MessageService

<Loader OnLoad="@OnLoad" LoadKey="@Id" UseSkeleton>
    <AntDesign.Comment Avatar="@Utils.GetGravatarUrl(Comment.Email)" @key="@Id">
        <DatetimeTemplate>
            <Tooltip Title="@(Comment.CreationTime.ToString("yyyy-MM-dd HH:mm:ss"))">
                <span>
                    @Comment.CreationTime.ToFriendlyString()
                </span>
            </Tooltip>
        </DatetimeTemplate>
        <ContentTemplate>
            @((MarkupString)RawContent)
            <AuthorizeView>
                <Authorized>
                    <Popconfirm Title="@($"Are you sure {(IsDeleted ? "revert" : "delete")} this comment?")" OnConfirm="OnDelete" Placement="@PlacementType.BottomRight">
                        <Button Danger="@(!IsDeleted)">
                            <MdiIcon Type="@(IsDeleted ? IconNames.Revert : IconNames.Delete)"></MdiIcon>
                            <span>@(IsDeleted ? "Revert" : "Delete")</span>
                        </Button>
                    </Popconfirm>
                </Authorized>
            </AuthorizeView>
        </ContentTemplate>
        <AuthorTemplate>
            <span>
                <a href="@Comment.Link">@Comment.Author</a>
                @if (ShowSource)
                {
                    <span>@@</span>
                    <a href="@Comment.Uri">
                        @Comment.Uri
                    </a>
                }
            </span>
        </AuthorTemplate>
    </AntDesign.Comment>
</Loader>

@code {
    [Parameter]
    public string Id { get; set; }

    [Parameter]
    public bool ShowSource { get; set; } = false;

    private AcBlog.Data.Models.Comment Comment { get; set; }

    private string RawContent { get; set; } = string.Empty;

    private bool IsDeleted { get; set; }

    private async Task OnLoad()
    {
        Comment = await Service.CommentService.Get(Id);

        RawContent = await MarkdownService.RenderHtml(Comment.Content);
    }

    private async Task OnDelete()
    {
        if (IsDeleted)
        {
            var pass = await Service.CommentService.Create(Comment);
            if (!string.IsNullOrWhiteSpace(pass))
            {
                IsDeleted = false;
                _ = MessageService.Success("Reverted comment successfully.");
            }
            else
            {
                _ = MessageService.Error("Failed to revert comment.");
            }
        }
        else
        {
            var pass = await Service.CommentService.Delete(Comment.Id);
            if (pass)
            {
                IsDeleted = true;
                _ = MessageService.Success("Deleted comment successfully.");
            }
            else
            {
                _ = MessageService.Error("Failed to delete comment.");
            }
        }
    }
}
